﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.Security;

namespace One.Framework.UI.Security
{
    public class HttpSecureCookie
    {
        /// <summary>
        /// 쿠키 복재
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static HttpCookie CloneCookie(HttpCookie cookie)
        {
            HttpCookie clonedCookie = new HttpCookie(cookie.Name, cookie.Value);
            clonedCookie.Domain = cookie.Domain;
            clonedCookie.Expires = cookie.Expires;
            clonedCookie.HttpOnly = cookie.HttpOnly;
            clonedCookie.Path = cookie.Path;
            clonedCookie.Secure = cookie.Secure;

            return clonedCookie;
        }


        /// <summary>
        /// 값이 엔코딩된 쿠키를 복재해 리턴한다.
        /// </summary>
        /// <param name="cookie"></param>
        /// <param name="cookieProtection"></param>
        /// <returns></returns>
        public static HttpCookie Encode(HttpCookie cookie, CookieProtection cookieProtection)
        {
            HttpCookie encodedCookie = CloneCookie(cookie);
            encodedCookie.Value =
                MachineKeyCryptography.Encode(cookie.Value, cookieProtection);
            return encodedCookie;
        }

        /// <summary>
        /// 기본 CookieProtection.All 인 경우 처리
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static HttpCookie Encode(HttpCookie cookie)
        {
            return Encode(cookie, CookieProtection.All);
        }


        /// <summary>
        /// 복호화된 값을 갖는 쿠키를 복재해 리턴
        /// </summary>
        /// <param name="cookie"></param>
        /// <param name="cookieProtection"></param>
        /// <returns></returns>
        public static HttpCookie Decode(HttpCookie cookie, CookieProtection cookieProtection)
        {
            HttpCookie decodeCookie = CloneCookie(cookie);
            decodeCookie.Value = MachineKeyCryptography.Decode(cookie.Value, cookieProtection);

            return decodeCookie;
        }

        /// <summary>
        /// protection = all 로 복호화 후 복재해 리턴
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static HttpCookie Decode(HttpCookie cookie)
        {
            return Decode(cookie, CookieProtection.All);
        }

    }
}
